
//---------------------------------------------------------------- INCLUDE

//-------------------------------------------------------- Include système
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdlib.h>
#include <cstring>
#include <unistd.h>
#include <stdio.h>

//------------------------------------------------------ Include personnel
#include "Communication.h"


//------------------------------------------------------------- Constantes

//----------------------------------------------------------------- PUBLIC

//----------------------------------------------------- Méthodes publiques
char Communication::SetPosition(int pos_left, int pos_right)
{
	char command[50];
	char reponse[3];
	sprintf (command, "C,%d,%d\n", pos_left, pos_right);
	write(fd, &command, sizeof(command));
	read(fd, &reponse, 3);
	return reponse[0];
}

char Communication::SetSpeed(int speed_motor_left, int speed_motor_right)
{
	char command[50];
	char reponse[3];
	int error;
	sprintf (command, "D,%d,%d\n", speed_motor_left, speed_motor_right);
	write(fd, &command, sizeof(command));
	read(fd, &reponse, 3);
	return reponse[0];
}

//------------------------------------------------- Surcharge d'opérateurs


//-------------------------------------------- Constructeurs - destructeur
Communication::Communication()
{
	/*Open port*/
	fd = open(DEVICE, O_RDWR | O_NOCTTY | O_NONBLOCK); 
	
	if (fd <0) {perror(DEVICE); exit(-1); }

	tcgetattr(fd,&oldtio); /* save current serial port settings */
	bzero(&newtio, sizeof(newtio)); /* clear struct for new port settings */

	/* 
	  BAUDRATE: Set bps rate. You could also use cfsetispeed and cfsetospeed.
	  CS8     : 8n1 (8bit,no parity, 1 stop bit)
	  CLOCAL  : local connection, no modem contol
	  CREAD   : enable receiving characters
	  CRTSCTS : contrôle de flux matériel (uniquement utilisé si le câble a
		    les lignes nécessaires.).
	  CS8     : 8n1 (8 bits,sans parité, 1 bit d'arrêt)
	*/
	newtio.c_cflag = CLOCAL | CREAD & ~CRTSCTS | CS8 | BAUDRATE;

	/*
	IGNPAR : ignore bytes with parity errors
	IGNBRK : ignore break condition. 
	*/
	newtio.c_iflag = IGNPAR | IGNBRK;

	/*
	Raw output.
	*/
	newtio.c_oflag = 0;

	/*
	ECHO:Enable echo.
	*/
	newtio.c_lflag = ~ECHO;

	/* 
	now clean the line and activate the settings for the port
	*/
	tcflush(fd, TCIFLUSH);
	int erreur = tcsetattr(fd,TCSANOW,&newtio);
	printf("%d/n",erreur);
}

Communication::~Communication()
{
	tcsetattr(fd,TCSANOW,&oldtio);
}

//------------------------------------------------------------------ PRIVE

//----------------------------------------------------- Méthodes protégées







